package com.chen;

import org.opencv.core.Mat;
import org.opencv.core.Core;
import org.opencv.core.MatOfRect;
import org.opencv.core.Range;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.videoio.VideoCapture;

/**
 * 素材生成器
 *
 * @author scorpius
 */
public class MaterialGenerator {

    static final String path = "/usr/local/share/opencv4/haarcascades/haarcascade_frontalface_default.xml";
    static int count = 0;

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        CascadeClassifier cascade = new CascadeClassifier(path);
        if (cascade.empty()) {
            System.err.println("文件载入错误...");
            return;
        }

        Mat imag = new Mat();

        VideoCapture capture = new VideoCapture();
        if (!capture.open(0)) {
            System.err.println("相机打开失败...");
            return;
        }

        while (true) {
            capture.read(imag);
            MatOfRect faces = new MatOfRect();//某张脸
            cascade.detectMultiScale(imag, faces);
            if (faces.size().empty()) {
                continue;
            }
            Rect[] rects = faces.toArray();
            Mat face = null;
            for (Rect rect : rects) {
                Imgproc.rectangle(imag, rect, new Scalar(0, 0, 255));
                Range r1 = new Range(rect.y, rect.y + rect.height); //脸坐标标记
                Range r2 = new Range(rect.x, rect.x + rect.width);//脸坐标标记
                face = new Mat(imag, r1, r2);//标准脸矩形标记
                Imgproc.resize(face, face, new Size(92, 112));//修改尺寸
                Imgproc.cvtColor(face, face, Imgproc.COLOR_BGR2GRAY);//灰度化

                HighGui.imshow("test", face);
            };
            StringBuilder sb = new StringBuilder();
            int key = HighGui.waitKey(100);

            //按q/Q键截图并保存
            if ((char) key == 'q' || (char) key == 'Q') {
                //请保证此路径下的目录是存在的，库不会自动给你创建目录
                sb.append("/home/scorpius/Pictures/orl_faces/s41/");
                sb.append(count++).append(".jpg");
                if (Imgcodecs.imwrite(sb.toString(), face)) {
                    System.out.println("保存成功");
                } else {
                    System.out.println("保存失败");
                }
            }
        }
    }
}
